from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from typing import Optional

engine = None
SessionLocal: Optional[sessionmaker] = None

Base = declarative_base()


def get_db():
    return SessionLocal()


def init_database(database_uri):
    """初始化engine、session-maker、建表"""
    global engine, SessionLocal
    if engine is None:
        engine = create_engine(
            database_uri,
            pool_size=10,
            max_overflow=0,
            pool_recycle=2 * 3600
        )
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        Base.metadata.create_all(engine)
